import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { WebsiteService } from './website.service';
import { MakeGqlAuthPowerGuard, UPDATE_POWER } from 'src/auth/auth.guard';
import { UseGuards } from '@nestjs/common';
import { FileService } from '@app/file';
import { WebsiteBasicInfoEntity } from './website.basic.info.entity';


export const WebsiteGuard = MakeGqlAuthPowerGuard("/website", "网站管理")
@Resolver()
export class WebsiteResolver {
  constructor(
    private readonly service: WebsiteService,
    private readonly file: FileService
  ) { }


  //试卷下载页面内容
  @Query(() => String)
  getWebsiteExams() {
    return this.file.readFile(this.service.getExamsPath())?.toString("utf-8") || ""
  }

  @Mutation(() => Boolean)
  @UseGuards(WebsiteGuard([UPDATE_POWER]))
  updateWebsiteExams(
    @Args("context") context: string
  ) {
    this.file.writeFile(this.service.getExamsPath(), context)
    return true
  }


  //站点介绍
  @Query(() => String)
  getWebsiteIntroduce() {
    return this.file.readFile(this.service.getIntroducePath())?.toString("utf-8") || ""
  }

  @Mutation(() => Boolean)
  @UseGuards(WebsiteGuard([UPDATE_POWER]))
  updateWebsiteIntroduce(
    @Args("context") context: string
  ) {
    this.file.writeFile(this.service.getIntroducePath(), context)
    return true;
  }



  @Query(() => WebsiteBasicInfoEntity)
  getWebsiteBasicInfo() {
    const res = JSON.parse(this.file.readFile(this.service.getBasicInfoPath())?.toString("utf-8") || this.service.websiteBasicInfoDefault);
    return res;
  }
  //修改 

  @Mutation(() => WebsiteBasicInfoEntity)
  @UseGuards(WebsiteGuard([UPDATE_POWER]))
  updateWebsiteBasicInfo(
    @Args("phone", { nullable: true }) phone?: string,
    @Args("email", { nullable: true }) email?: string,
    @Args("wechat", { nullable: true }) wechat?: string,
    @Args("postalCode", { nullable: true }) postalCode?: string,
    @Args("address", { nullable: true }) address?: string,
    @Args("qqGroupQRCode", { nullable: true }) qqGroupQRCode?: string,
    @Args("webmasterWechat", { nullable: true }) webmasterWechat?: string,
  ) {
    const data = this.file.readFile(this.service.getBasicInfoPath())?.toString("utf-8") || this.service.websiteBasicInfoDefault;
    const newData: WebsiteBasicInfoEntity = JSON.parse(data);
    if (!!phone) newData.phone = phone;
    if (!!email) newData.email = email;
    if (!!wechat) newData.wechat = wechat;
    if (!!postalCode) newData.postalCode = postalCode;
    if (!!address) newData.address = address;
    if (!!qqGroupQRCode) newData.qqGroupQRCode = qqGroupQRCode;
    if (!!webmasterWechat) newData.webmasterWechat = webmasterWechat;
    this.file.writeFile(this.service.getBasicInfoPath(), JSON.stringify(newData));
    return newData;
  }






}
